<template>
  <ClientOnly>
    <div
      class="w-[100%] h-[100%] flex items-center justify-between header-nav"
      :style="{paddingTop:100 * (20 / screensStore.bodyHeight) + 'vh',paddingBottom:100 * (20 / screensStore.bodyHeight) + 'vh',
   paddingLeft:100 * (20 / screensStore.bodyWidth) + 'vw',paddingRight:100 * (20 / screensStore.bodyWidth) + 'vw',
   background:screensStore.selProjectObj.projectStyle || '#fff'}"
      style="box-shadow: 0 0 10px 0 rgba(0,0,0,0.3)">
      <div class="fixed-row">
        <img :src="JSON.parse(screensStore.selProjectObj.logoUrl)[0].url" style="width: 150px;height: 100px"
             v-if="screensStore.selProjectObj.logoUrl">
        <h3 style="margin-left: 10px;font-size: 20px;font-weight: 700">{{ screensStore.brandName }}</h3>
      </div>
      <div class="fixed-column-item">
        <div class="fixed-row" style="margin-bottom: 5px">
          <div class="fixed-row">
            <el-select v-model="screensStore.selProjectId" placeholder="请选择项目" style="width: 240px"
                       v-if="screensStore.projectSet.length" @change="changeProject">
              <el-option
                v-for="item in screensStore.projectSet"
                :key="item.id"
                :label="item.projectName"
                :value="item.id"
              />
            </el-select>
          </div>
          <!--        <img src="https://www.knschina.cn/Public/Home/images/icon_9.png" title="神秘客二维码">-->
          <div style="margin: 0 20px" class="enter-shenmi">
            <el-button type="primary" round class="target-proint" @click="toShen">神秘客入口</el-button>
          </div>

          <div>
            <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
              <div class="avatar-wrapper">
                <el-tooltip :content="'账号：' + screensStore.user.userName" placement="bottom" effect="light">
                  <img :src="screensStore.user.avatar ? screensStore.user.avatar : '/profile.jpg'" class="user-avatar">
                  <i class="el-icon-caret-bottom" />
                </el-tooltip>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click.native="logout">
                    <span>退出登录</span>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        <div class="nav-header-to">
          <el-menu
            :default-active="screensStore.activeHomeNav"
            class="el-menu-demo"
            mode="horizontal"
            :ellipsis="false"
            @select="selectNav"
            :background-color="screensStore.selProjectObj.projectStyle"
            :text-color="'#fff'"
            :active-text-color="'#041850'"
          >
            <template v-for="item in screensStore.menuNav" :key="item.name">
              <el-menu-item v-if="!item.children" :index="item.name" :key="item.name">
                <NuxtLink
                  :to="item.path + (screensStore.periodId && item.name != '项目概述' && item.name != '期次选择' ? '?periodId='+screensStore.periodId : '')">
                  <template v-if="item.hasOwnProperty('isShow') && item.isShow == false">
                    <div>{{item.name}}</div>
                  </template>
                  <template v-else>
                    <el-badge :value="item.num" class="item" :offset="[10, 12]">
                      <div>{{item.name}}</div>
                    </el-badge>
                  </template>
                </NuxtLink>
              </el-menu-item>
              <el-sub-menu v-if="item.children" :index="item.name" :key="item.name">
                <template #title>{{item.name}}</template>
                <el-menu-item v-for="itemChild in item.children" :key="itemChild.name" :index="itemChild.meta.title">
                  <NuxtLink
                    :to="item.path + '/' + itemChild.path + (screensStore.periodId && item.name != '项目概述' && item.name != '期次选择' ? '?periodId='+screensStore.periodId : '')">
                    <template v-if="item.hasOwnProperty('isShow') && item.isShow == false">
                      <div>{{itemChild.meta.title}}</div>
                    </template>
                  </NuxtLink>
                </el-menu-item>
              </el-sub-menu>
            </template>
          </el-menu>
        </div>
      </div>
    </div>
  </ClientOnly>

</template>

<script setup lang="ts">
  import { onMounted } from 'vue'
  import { removeItem } from '~/utils'
  import { screenStore } from '~/stores/modules/screen'
  import { storeToRefs } from 'pinia'
  import { useRouter } from 'vue-router'
  import { getRouters,setHistoryProject } from '~/api/public'
  let jiaobiao = null
  const router = useRouter()
  const screensStore = screenStore()
  onBeforeUnmount(()=>{
    if(jiaobiao){
      jiaobiao.close()
    }
  })
  watch(() => screensStore.selProjectObj, (val) => {
    //切换项目进行保存历史项目
    if(sessionStorage.getItem('showLogin')){
      const data = {
        brandId:getItem('pinpaiId'),
        projectId:screensStore.selProjectId
      }
      setHistoryProject(data)
      if (!val.projectDesc) {
        screensStore.menuNav = screensStore.menuNav.filter(item => item.name != '项目概述')
        screensStore.activeHomeNav = screensStore.menuNav[0].name
        router.push({ path: screensStore.menuNav[0].path })
      } else {
        screensStore.menuNav = [
          { name: '项目概述', children: null, path: '/projectdesp',isShow:false },
          { name: '期次选择', children: null, path: '/issueselect',isShow:false }
        ]
        screensStore.activeHomeNav = '项目概述'
        router.push({ path: '/projectdesp' })
      }
      getRouters().then(res => {
        if (res.code == 200) {
          const arr = res.data.filter(item => {
            if(item.hasOwnProperty('meta')){
              if (item.meta.title == '访问计划') return true
              else if (item.meta.title == '数据审核') return true
              else if (item.meta.title == '申诉审核') return true
              else if (item.meta.title == '整体进度') return true
              else if (item.meta.title == '报表查看') return true
              else if (item.meta.title == '网点申诉') return true
              else if (item.meta.title == '任务大厅') return true
            }
            return false
          })
          arr.forEach(item => {
            screensStore.menuNav.push({ name: item.meta.title, children: item.children, path: item.path,isShow:false,num:0 })
          })
          // 进行sse连接
          const pinpaiId = getItem('pinpaiId')
          //todo 待修改
          jiaobiao = new EventSource(`http://129.211.212.235:8095/base/cornermarks/events?brandId=${pinpaiId}&userId=${screensStore.user.userId}`)
          jiaobiao.addEventListener('message',(res) => {
            if(res.data){
              const obj = JSON.parse(res.data)
              const keys = Object.keys(obj)
              for(let key of keys){
                const ind = screensStore.menuNav.findIndex(itemKey => itemKey.path.includes(key))
                if(obj[key] != 0){
                  if(ind != -1){
                    screensStore.menuNav[ind].isShow = true
                    screensStore.menuNav[ind].num = obj[key]
                    continue
                  }
                }
                else{
                  if(ind != -1){
                    screensStore.menuNav[ind].isShow = false
                    screensStore.menuNav[ind].num = 0
                    continue
                  }
                  continue
                }
              }
            }
          })
          jiaobiao.addEventListener('error',(res) => {
            console.log(res,'sse连接错误')
          })
        } else {
          ElMessage.error(res.msg || '路由信息获取失败')
        }
      })
    }
  }, { deep: true })

  function selectNav(MenuSelectEvent) {
    screensStore.activeHomeNav = MenuSelectEvent
  }

  function changeProject(id: string) {
    const ind = screensStore.projectSet.findIndex(item => item.id == id)
    screensStore.selProjectObj = screensStore.projectSet[ind]
  }

  function logout() {
    ElMessageBox.confirm(
      '是否确认退出登录！',
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
      .then(() => {
        const data = {
          brandId:getItem('pinpaiId'),
          projectId:screensStore.selProjectId
        }
        setHistoryProject(data).then(res => {
          screensStore.brandName = ''
          screensStore.activeHomeNav = ''
          screensStore.projectSet = []
          screensStore.selProjectId = ''
          screensStore.selProjectObj = {}
          screensStore.menuNav = [
            { name: '项目概述', children: null, path: '/projectdesp' },
            { name: '期次选择', children: null, path: '/issueselect' },
            { name: '访问计划', children: null, path: '/planvisit' },
            { name: '数据审核', children: null, path: '/dataaudit' },
            { name: '申诉审核', children: null, path: '/appealaudit' },
            { name: '整体进度', children: null },
            { name: '报表查看', children: null, path: '/statementview' },
            { name: '网点申诉', children: null, path: '/branchappeal' }
          ]
          screensStore.periodId = ''
          screensStore.selPeriodObj = {}
          screensStore.proviceList = []
          screensStore.userInfo = {}
          screensStore.user = {}
          screensStore.roles = []
          removeItem('token')
          sessionStorage.removeItem('showLogin')
          ElMessage.success('退出登录')
          setTimeout(() => {
            router.replace({ path: '/userhome?id=' + getItem('pinpaiId') })
          }, 1500)
        })
      })
  }

  function toShen() {
    window.open('http://129.211.212.235:8095:8735/')
  }
</script>

<style scoped lang="less">
  .header-nav {
    height: 125px;
    position: fixed;
    top: 0;
    z-index: 100;
  }

  .enter-shenmi ::v-deep .el-button {
    background: #041850 !important;
  }

  .top-nav-router li:not(:first-child) > div {
    display: inline-block;

    &:hover {
      cursor: pointer;
    }
  }

  .top-nav-router li:not(:first-child)::before {
    content: '/';
    display: inline-block;
    margin: 0 10px;
  }

  ::v-deep .el-menu--horizontal>.el-sub-menu.is-active .el-sub-menu__title{
    color: #041850 !important;
    font-size: 15px !important;
    border-bottom: 2px solid #041850;
  }
  .nav-header-to .el-menu--horizontal > .el-menu-item.is-active {
    color: #041850 !important;
    font-size: 15px !important;
    border-bottom: 2px solid #041850;
  }

  .nav-header-to .el-menu-horizontal > .el-sub-menu:hover .el-sub-menu_title {
    color: #041850 !important;
  }

  .nav-header-to .el-menu--horizontal.el-menu {
    border-bottom: none;
  }

  .avatar-container {
    .avatar-wrapper {
      margin-top: 5px;
      position: relative;

      .user-avatar {
        cursor: pointer;
        width: 40px;
        height: 40px;
        border-radius: 10px;
      }

      .el-icon-caret-bottom {
        cursor: pointer;
        position: absolute;
        right: -20px;
        top: 25px;
        font-size: 12px;
      }
    }
  }
</style>
